﻿// register your Gadget's namespace
registerNamespace("Gadget.Springnote");

Gadget.Springnote.GoButton = function(p_elSource, p_args, p_namespace) {
	Gadget.Springnote.GoButton.initializeBase(this, arguments);
	
	var m_this = this;
	var m_id = p_args.id;
	
	function goClick(){
		m_this.fire("onclick",{id:m_id});
	}
	this.initialize = function(p_objScope){
        Gadget.Springnote.GoButton.getBaseMethod(this, "initialize", "Web.Bindings.Base").call(this, p_objScope);
        p_elSource.attachEvent("onclick",goClick);
    };
    
    this.dispose = function(p_blnUnload){
        p_elSource.detachEvent("onclick",goClick);		
        Gadget.Springnote.GoButton.getBaseMethod(this, "dispose", "Web.Bindings.Base").call(this, p_blnUnload);
    };
}
Gadget.Springnote.GoButton.registerClass("Gadget.Springnote.GoButton", "Web.Bindings.Base");
Gadget.Springnote.GoButton.Events = Web.Enum.create("onclick");

// define the constructor for your Gadget (this must match the name in the manifest xml)
Gadget.Springnote.OpenBrain = function(p_elSource, p_args, p_namespace) {
    // always call initializeBase before anything else!
	Gadget.Springnote.OpenBrain.initializeBase(this, arguments);

    // setup private member variables
	var m_this = this;
	var m_el = p_elSource;
	var m_module = p_args.module;
    
    var doc = m_el.document;
    
    var div_setting = null;
    var t_openid = null;
    var t_userkey = null;
    var bt_settingok = null;
    var bt_settingcancel = null;
    var bt_settingshow = null;
    
    var div_resultlayout = null;
    var div_resultlistlayout = null;
    var div_addlayout = null;
    var div_updatelayout = null;
    var div_message = null;
    
    var t_keyword = null;
    var bt_search = null;
    var bt_update = null;
    var bt_delete = null;
    var bt_updateok = null;
    var bt_updatecancel = null;
    var bt_addok  = null;
    var bt_addcancel = null;
    var idinresultlayout = null;
    var idinupdatelayout = null;
    
	/****************************************
	**          initialize Method
	****************************************/
    // initialize is always called immediately after your object is instantiated
	this.initialize = function(p_objScope)
	{
	    // always call the base object's initialize first!	
		Gadget.Springnote.OpenBrain.getBaseMethod(this, "initialize", "Web.Bindings.Base").call(this, p_objScope);
        //TODO: perform any initialization/setup work
        function loadHtml(response){
            if(response.status == 200){
                if(response.responseXML){
                    var htmlNodes = response.responseXML.selectNodes("Content[@type='html']");
                    for(var i = 0 ; i < htmlNodes.length ; i++){
                        m_el.innerHTML += htmlNodes[i].text;
                    }
                }
                init();
                bindEvent();          
            }
        }
        var req = Web.Network.createRequest(
            Web.Network.Type.XML,
            "http://gadgets.cafe24.com/gadgets/MSLiveGadget/htmlContent.xml",
            {proxy:"generic", numItems:5},
            loadHtml);
	    req.execute();
	   
	};
	Gadget.Springnote.OpenBrain.registerBaseMethod(this, "initialize");
	
	
	/****************************************	
	**           dispose Method
	****************************************/
	this.dispose = function(p_blnUnload) {
	    //TODO: add your dispose code here
	    
	    // null out all member variables
	    m_this = null;
	    m_el = null;
	    m_module = null;  
	    
        // always call the base object's dispose last!	
		Gadget.Springnote.OpenBrain.getBaseMethod(this, "dispose", "Web.Bindings.Base").call(this, p_blnUnload);
	};
	Gadget.Springnote.OpenBrain.registerBaseMethod(this, "dispose");

	/****************************************
	** Other Methods
	****************************************/
	function init(){
	    div_setting = doc.getElementById('setting');
	    t_openid = doc.getElementById('openid');
        t_userkey = doc.getElementById('userkey');
        bt_settingok = doc.getElementById('settingok');
        bt_settingcancel = doc.getElementById('settingcancel');
        bt_settingshow = doc.getElementById('settingshowbutton');
    
        div_resultlayout = doc.getElementById('resultlayout');
        div_resultlistlayout = doc.getElementById('resultlistlayout');
        div_addlayout = doc.getElementById('addlayout');
        div_updatelayout = doc.getElementById('updatelayout');
        div_message = doc.getElementById('message');
 
        t_keyword = doc.getElementById('keyword');
        bt_search = doc.getElementById('search');
        bt_update = doc.getElementById('update');
        bt_delete = doc.getElementById('delete');
        bt_updateok = doc.getElementById('updateok');
        bt_updatecancel = doc.getElementById('updatecancel');
        bt_addok  = doc.getElementById('addok');
        bt_addcancel = doc.getElementById('addcancel');
        
        idinresultlayout = doc.getElementById('idinresultlayout');
        idinupdatelayout = doc.getElementById('idinupdatelayout');
        
        onOpen();
	}
	function bindEvent(){
	    bt_settingok.attachEvent("onclick",onSettingOk);
	    bt_settingcancel.attachEvent("onclick",onSettingCancel);
	    bt_settingshow.attachEvent("onclick",onSettingShowClick);
	        
	    t_keyword.attachEvent("onkeypress",onTextKeyPress);
        bt_search.attachEvent("onclick",onSearchClick);
        bt_update.attachEvent("onclick",onUpdateClick);
        bt_delete.attachEvent("onclick",onDeleteClick);
        bt_updateok.attachEvent("onclick",onUpdateOkClick);
        bt_updatecancel.attachEvent("onclick",onUpdateCancelClick);  
        bt_addok.attachEvent("onclick",onAddOkClick);  
        bt_addcancel.attachEvent("onclick",onAddCancelClick);        
	}
    /****************************************
	** main.js
	****************************************/

var M_OPENID = "http://humbroll.myid.net";
var M_AJAXENGINE = null;
var M_QUERY = null;
var M_USERKEY = "1c86dd87a427a21f82644e95ae9711de0ce5a090";
var M_BASEURL = "http://[URL]/pages/[detailURL]?format=xml";

var M_MESSAGE_FAILED = "해당 글이 존재하지 않습니다.";
var M_MESSAGE_LOAD = "불러오는중...";

var M_LOC_CREATEDATE = 1;
var M_LOC_ID = 2;
var M_LOC_TITLE = 3;

function onOpen(){
	setUserInfo();
	M_AJAXENGINE = new ajaxEngine();
	M_AJAXENGINE.createXHR();
	M_QUERY = new queryEngine()
	
}
function setUserInfo(){
	M_OPENID = m_module.getPreference("OPENID");
	M_USERKEY = m_module.getPreference("USERKEY");
	if(M_OPENID == "" || M_OPENID == null ||  M_USERKEY =="" || M_USERKEY == null){
	    settingShow();
	}else{
	    t_openid.value = M_OPENID;
	    t_userkey.value = M_USERKEY;
	}
}

//EventMethod-----------------------------------------------------------------------
function onSettingShowClick(){
    t_openid.value = M_OPENID;
	t_userkey.value = M_USERKEY;
    settingShow();
}
function onSettingOk(){
    if(doc.getElementById('openid').value == "" || doc.getElementById('userkey').value == ""){
        alert("사용자 정보를 입력해주세요.");
        return;
    }
    m_module.setPreference("OPENID",t_openid.value);
    m_module.setPreference("USERKEY",t_userkey.value);
    settingClose();
    onOpen();
}
function onSettingCancel(){
    settingClose();
}
function onTextKeyPress(){
	if(event.keyCode == 27){
		t_keyword.value = "";
		return;
	}
	if(event.keyCode == 13){
		onSearchClick();
	}
}
function onSearchClick(){
	var m_keyWord = t_keyword.value;
	var m_query = M_QUERY.makeSearchQuery(m_keyWord.toLowerCase());
	if(m_keyWord == ""){
		alert("검색어를 입력해주세요^^");
		return;
	}
	if(m_query == null){
		renderMessage(M_MESSAGE_FAILED,15);
		return;
	}
	renderMessage(M_MESSAGE_LOAD,10);
	M_AJAXENGINE.openXHR("GET",m_query,handleSearchResult);
}
function onAddClick(){
	showAddLayout();
}
function onAddOkClick(){
	var m_title = doc.getElementById('addtitle').value;
	var m_content = doc.getElementById('addcontent').value;
	m_content = M_QUERY.htmlGenerator(m_content);
	var m_xml = M_QUERY.makeAddXMLPageQuery(m_title,m_content);
	var m_url = M_QUERY.makeAddPageQuery();
	M_AJAXENGINE.openXHR("POST",m_url,addResult,m_xml);
}
function onAddCancelClick(){
	doc.getElementById('addtitle').value = "";
	doc.getElementById('addcontent').value = "";
	showMessageLayout();
}
function onGoClick(e){
	M_AJAXENGINE.openXHR("GET",M_QUERY.makeGetPageQuery(e.Package.id),makePageHtml);
}
function onUpdateClick(){
	showUpdateLayout();
}
function onUpdateOkClick(){
	if(confirm("해당 글이 수정됩니다.")){
		var m_id = doc.getElementById('idinupdatelayout').value;
		var m_url = M_QUERY.makeGetPageQuery(m_id);
		var m_title = doc.getElementById('updatetitle').value;
		var m_content = M_QUERY.htmlGenerator(document.getElementById('updatecontent').value);
		var m_xml = M_QUERY.makeAddXMLPageQuery(m_title,m_content);
		M_AJAXENGINE.openXHR("PUT", m_url, updateResult, m_xml);
	}
}
function onUpdateCancelClick(){
	showResultLayout();
}
function onDeleteClick(){
	if(confirm("해당 글이 삭제됩니다.")){
		var m_id = doc.getElementById('idinresultlayout').value;
		M_AJAXENGINE.openXHR("DELETE", M_QUERY.makeGetPageQuery(m_id), deleteResult);
	}	
}
//-----------------------------------------------------------------------------
//CallBack Method--------------------------------------------------------------
function handleSearchResult(p_result){
	var m_pages = p_result.getElementsByTagName("page");
	if(m_pages.length == 0){
		showMessageLayout();
		div_message.innerHTML =  "<i><b>\"" + keyword.value + "\"</b></i>&nbsp페이지가 존재하지 않습니다. 추가하시겠습니까?&nbsp&nbsp";
		var newbutton = doc.createElement("img");
		newbutton.className = "button";
		newbutton.alt = "확인";
		newbutton.src = "http://gadgets.cafe24.com/gadgets/GoogleWebGadget/img/buttonOk.gif";
		newbutton.attachEvent('onclick',onAddClick);
		div_message.appendChild(newbutton);
		return;
	}
	for( var i = 0 ; i < m_pages.length ; i=i+1){
		if( (m_pages[i].childNodes[M_LOC_TITLE].firstChild.nodeValue).toLowerCase().replace(/ /g,'') == (keyword.value).toLowerCase().replace(/ /g,'') ){
			var m_page_id = m_pages[i].childNodes[M_LOC_ID].firstChild.nodeValue;
			M_AJAXENGINE.openXHR("GET",M_QUERY.makeGetPageQuery(m_page_id),makePageHtml);
			return;
		}
	}
	makePageListHtml(m_pages);
}
function makePageHtml(p_result){
	showResultLayout();
	var m_content = p_result.getElementsByTagName('source')[0].firstChild.nodeValue;
	var m_title = p_result.getElementsByTagName('title')[0].firstChild.nodeValue;
	var m_id = p_result.getElementsByTagName('identifier')[0].firstChild.nodeValue;
	doc.getElementById('resulttitle').innerHTML = m_title;
	doc.getElementById('resultcontent').innerHTML = m_content;
	doc.getElementById('idinresultlayout').value = m_id;
} 
function makePageListHtml(p_pages){
	    showResultListLayout();
		div_resultlistlayout.innerHTML = "";
		var m_contentlist = document.createElement("table");
		
	    var b_add = doc.createElement('b');
	    b_add.innerHTML = "<i>" + keyword.value + "</i>&nbsp페이지를 추가하시겠습니까?&nbsp&nbsp";
	    m_contentlist.appendChild(b_add);
	    var img_add = doc.createElement('img');
	    img_add.alt = "확인";
	    img_add.src = "http://gadgets.cafe24.com/gadgets/GoogleWebGadget/img/buttonOk.gif";
	    img_add.id = "new_page";
	    m_contentlist.appendChild(img_add);	   
		//m_contentlist.style.width = "320px";
		//m_contentlist.style.border = "1px solid #000";
		var m_div = doc.createElement("div");
		var m_tr = null;
		var m_tdTitle = null;
		for(var i = 0 ; i < p_pages.length ; i=i+1){
			m_tr = doc.createElement("tr");
			if(i%2 == 0){
				m_tr.className = "springnoteDialogBg";
			}
			m_tdTitle = doc.createElement("td");
			m_tdTitle.innerHTML = p_pages[i].childNodes[M_LOC_TITLE].firstChild.nodeValue;
			m_tr.appendChild(m_tdTitle);			
			m_tdGo = doc.createElement("td");
			m_tdGo.id = "bttd_" + i;			
			m_tr.appendChild(m_tdGo);
			m_contentlist.appendChild(m_tr);
		}
		m_div.appendChild(m_contentlist);
		div_resultlistlayout.innerHTML = m_div.innerHTML;
		
		doc.getElementById('new_page').attachEvent('onclick',onAddClick);
		for(var i = 0 ; i < p_pages.length ; i=i+1){
			var m_btGo = doc.createElement("a");
			m_btGo.appendChild(doc.createTextNode('바로가기'));
			m_btGo.href = "#";
			var m_tdId = "bttd_" + i;
			(document.getElementById(m_tdId)).appendChild(m_btGo);
			var m_boundBtGo = Web.Bindings.attachElementBindingSync(
				m_btGo
				, Gadget.Springnote.GoButton
				, m_this
				, {
					id : p_pages[i].childNodes[M_LOC_ID].firstChild.nodeValue
			});
			m_boundBtGo.attachEvent("onclick",onGoClick);
			m_btGo = null;
		}
}
function addResult(p_result){
	var m_errorMsg = checkError(p_result);
	if(m_errorMsg === "noerror"){
		makePageHtml(p_result);
		message.style.display = "block";
		message.innerHTML = "<font color=\"red\"><b><i>추가 성공~!</i></b></font>";
	}else{
		alert(m_errorMsg);
		return;
	}
}
function updateResult(p_result){
	var m_errorMsg = checkError(p_result);
	if(m_errorMsg === "noerror"){
		makePageHtml(p_result);
		doc.getElementById('message').style.display = "block";
		doc.getElementById('message').innerHTML = "<font color=\"red\"><b><i>수정 성공~!</i></b></font>";
	}else{
		alert(m_errorMsg);
		return;
	}
}
function deleteResult(p_result){
	var m_errorMsg = checkError(p_result);
	if(m_errorMsg === "noerror"){
		showMessageLayout();
		div_message.innerHTML = "<font color=\"red\"><b><i>삭제 성공~!</i></b></font>";
	}else{
		alert(m_errorMsg);
		return;
	}
}
//-----------------------------------------------------------------------------
//layout handler---------------------------------------------------------------
function settingShow(){
    div_setting.style.display = "block";
}
function settingClose(){
    div_setting.style.display = "none";
}
function showMessageLayout(){ 
	div_message.style.display = "block";
	div_message.innerText = "";
	div_resultlistlayout.style.display = "none";
	div_resultlayout.style.display = "none";
	div_updatelayout.style.display = "none";
	div_addlayout.style.display = "none";
}
function showResultLayout(){
	div_message.style.display = "none";
	div_resultlistlayout.style.display = "none";
	div_resultlayout.style.display = "block";
	doc.getElementById('resulttitle').value = "";
	doc.getElementById('resultcontent').value = "";
	div_updatelayout.style.display = "none";
	div_addlayout.style.display = "none";
}
function showResultListLayout(){
	div_message.style.display = "none";
	div_resultlistlayout.style.display = "block";
	div_resultlayout.style.display = "none";
	div_updatelayout.style.display = "none";
	div_addlayout.style.display = "none";
}
function showUpdateLayout(){
	var m_title = doc.getElementById('resulttitle').innerText;
	var m_content = doc.getElementById('resultcontent').innerText;
	var m_id = doc.getElementById('idinresultlayout').value;
	div_message.style.display = "none";
	div_resultlistlayout.style.display = "none";
	div_resultlayout.style.display = "none";
	div_updatelayout.style.display = "block";
	div_addlayout.style.display = "none";
	doc.getElementById('updatetitle').value = m_title;
	doc.getElementById('updatecontent').value = m_content;
	doc.getElementById('idinupdatelayout').value = m_id;
}
function showAddLayout(){
	div_message.style.display = "none";
	div_resultlistlayout.style.display = "none";
	div_resultlayout.style.display = "none";
	div_updatelayout.style.display = "none";
	div_addlayout.style.display = "block";
	doc.getElementById('addtitle').value = keyword.value;
	doc.getElementById('addcontent').value = "";
}
function checkError(p_xml){
	var m_page = p_xml.getElementsByTagName('page');
	if(m_page.length != 0){
		return "noerror";
	}
	else{
		var m_errorMsg = p_xml.getElementsByTagName('error')[0].firstChild.nodeValue;
		return m_errorMsg;
	}
}
//util method & etc-----------------------------------------------------------------------------
//rendering method
//@param p_string : result string
//@param p_size   : font size
function renderMessage(p_string,p_size){
	if(p_size != -1){
		p_string = "<div style=\"font-family:tahoma;font-size:" + p_size + "px;\">" + p_string + "</div>";	
	}
	message.innerHTML = p_string;
}
    /****************************************
	** ajaxEngine.js
	****************************************/

var READY_STATE_UNINITIALIZED = 0;
var READY_STATE_LOADIN = 1;
var READY_STATE_LOADED = 2;
var READY_STATE_INTERACTIVE = 3;
var READY_STATE_COMPLETE = 4;

var SUCCESS_RECIEVE = 200;
var BAD_REQUEST = 400;
var UNAUTHENTICATED = 401;
var NOT_FOUND = 404;
var INTERNAL_SERVER_ERROR = 500;

function ajaxEngine(){
	this.m_callBack = null;
	this.m_XHR = null;
}
ajaxEngine.prototype.createXHR = function(){
	try{
		this.m_XHR = new XMLHttpRequest();
	}catch(e){
		try{
			this.m_XHR = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(e){
			try{
				this.m_XHR = new ActiveXObejct("Msxml2.XMLHTTP");
			}catch(e){
				return null;
			}
		}
	}
}
ajaxEngine.prototype.openXHR = function(p_method,p_url,p_callBack,p_content){
	this.m_callBack = p_callBack;
	if(p_method.toLowerCase() == "get"){
		this.openXHRGET(p_url,p_callBack);
	}else if(p_method.toLowerCase() == "post"){
		this.openXHRPOST(p_url,p_callBack,p_content);
	}else if(p_method.toLowerCase() == "put"){
		this.openXHRPUT(p_url,p_callBack,p_content);
	}else if(p_method.toLowerCase() == "delete"){
		this.openXHRDELETE(p_url,p_callBack);
	}
}
ajaxEngine.prototype.openXHRGET = function(p_url,p_callBack){
	try{
		this.m_XHR.open("GET",encodeURI(p_url),true);
		this.m_XHR.setRequestHeader("Authorization", getAuth(M_OPENID,M_USERKEY));
		
	}catch(e){
		alert("exception in XHR's open or setRequestHeader - GET");
		return;
	}
	var m_loader = this;
	this.m_XHR.onreadystatechange = function(){ m_loader.callBack(m_loader); };
	try{
		this.m_XHR.send(null);
	}catch(e){
		alert("exception in XHR's send - GET");
		return;
	}	
}
ajaxEngine.prototype.openXHRPOST = function(p_url,p_callBack,p_content){
	try{
		this.m_XHR.open("POST",encodeURI(p_url),true);
		this.m_XHR.setRequestHeader("Authorization", getAuth(M_OPENID,M_USERKEY));
	}catch(e){
		debug("exception in XHR's open or setRequestHeader - POST");
		return;
	}
	var m_loader = this;
	this.m_XHR.onreadystatechange = function(){ m_loader.callBack(m_loader); };
	try{
		this.m_XHR.send(p_content);
	}catch(e){
		debug("exception in XHR's send - POST");
		return;
	}
}
ajaxEngine.prototype.openXHRPUT = function(p_url,p_callBack,p_content){
	try{
		this.m_XHR.open("PUT",encodeURI(p_url),true);
		this.m_XHR.setRequestHeader("Authorization", getAuth(M_OPENID,M_USERKEY));
	}catch(e){
		alert("exception in XHR's open or setRequestHeader - PUT");
		return;
	}
	var m_loader = this;
	this.m_XHR.onreadystatechange = function(){ m_loader.callBack(m_loader); };
	try{
		this.m_XHR.send(p_content);
	}catch(e){
		alert("exception in XHR's send - PUT");
		return;
	}
}
ajaxEngine.prototype.openXHRDELETE = function(p_url,p_callBack){
	try{
		this.m_XHR.open("DELETE",encodeURI(p_url),true);
		this.m_XHR.setRequestHeader("Authorization", getAuth(M_OPENID,M_USERKEY));
	}catch(e){
		alert("exception in XHR's open or setRequestHeader - DELETE");
		return;
	}
	var m_loader = this;
	this.m_XHR.onreadystatechange = function(){ m_loader.callBack(m_loader); };
	try{
		this.m_XHR.send(null);
	}catch(e){
		alert("exception in XHR's send - DELETE");
		return;
	}	
}
ajaxEngine.prototype.callBack = function(p_loader){
	//alert("p_loader.m_XHR.readyState : "  + p_loader.m_XHR.readyState);
	if(p_loader.m_XHR.readyState != READY_STATE_COMPLETE){
		return;
	}
	//alert("p_loader.m_XHR.status : " + p_loader.m_XHR.status);
	if(p_loader.m_XHR.status != SUCCESS_RECIEVE){
		if(p_loader.m_XHR.status == BAD_REQUEST){
			alert("Reqeust Message is ivalid\mConfirm your request message.\n(xml/json)");
		}else if(p_loader.m_XHR.status == UNAUTHENTICATED){
			alert("Unauthenticated");
		}else if(p_loader.m_XHR.status == NOT_FOUND){
			alert("Not found.");
		}else if(p_loader.m_XHR.status == INTERNAL_SERVER_ERROR){
			alert("Internal server error");
		}
	}
	var result = p_loader.m_XHR.responseXML;
	p_loader.m_callBack(result);
}
    /****************************************
	** queryEngine.js
	****************************************/
var M_BASEURL = "http://api.springnote.com/pages[detailURL]";

function queryEngine(){
	//this.m_baseURL = M_BASEURL.replace('[ID]',M_ID);
	this.m_baseURL = M_BASEURL;
}
queryEngine.prototype.makeSearchQuery = function(p_keyWord){
	var m_url = this.m_baseURL;
	m_url = m_url.replace('[detailURL]',"/search.xml?fulltext=1&q=" + p_keyWord);
	return m_url;
}
queryEngine.prototype.makeGetPageQuery = function(p_page_id){
	var m_url = this.m_baseURL;
	m_url = m_url.replace('[detailURL]',"/" + p_page_id + ".xml");
	return m_url;
}
queryEngine.prototype.makeAddPageQuery = function(){
	var m_url = this.m_baseURL;
	m_url = m_url.replace('[detailURL]',".xml");
	return m_url;
}
queryEngine.prototype.makeAddXMLPageQuery = function(p_title,p_content){
	var m_content_xml = "<?xml version='1.0' encoding='UTF-8'?>" 
						+ "<page>"
						+ "<source> [source] </source>"
						+ "<title> [title] </title>"
						+ "</page>";
	m_content_xml = m_content_xml.replace('[title]',p_title);
	p_content = this.htmlGenerator(p_content);
	m_content_xml = m_content_xml.replace('[source]',p_content);
	return m_content_xml;
}
queryEngine.prototype.htmlGenerator = function(p_string){
	p_string = p_string.replace(/\r\n/g,"&lt;br/&gt;");
	return p_string	
}
//deprecated---------------------------------------------------------
queryEngine.prototype.getIDbyKeyWord = function(p_keyWord){
	var pages = M_PAGES.getElementsByTagName("page");
	var m_name = "";
	for(var i = 1 ; i <  pages.length ; i++){
		m_name = pages[i].childNodes[1].firstChild.nodeValue;
		if(m_name == p_keyWord){
			return pages[i].childNodes[0].firstChild.nodeValue;
		}
	}
}
//-------------------------------------------------------------------
    /****************************************
	** auth.js
	****************************************/
///////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright 2007 humbroll - WOC.  All rights reserved.
//
///////////////////////////////////////////////////////////////////////////////////////////////////

var devKey = "79fe1c017f513cc888aaaf3a697bfd4dbd014ce0";
var devId = "2";

function getAuth(p_id,p_userKey){
	var userKey = p_userKey;
    var nonce = generateNonce();
    var created = getCreated();
    var keydigest = SHA1(nonce + created + userKey + devKey);
    var password = encodeURIComponent(devId + "," + nonce + "," + created + "," + keydigest);
	var auth = "Basic " + Base64.encode(encodeURIComponent(p_id) + ":" + password);
	
	return auth;
}
function generateNonce(){
   	var nonce = "";
   	for (var i = 0; i < 16; i++) {
		nonce += Math.floor(Math.random() * 16).toString(16);
   	}
   	return nonce;
}
function getCreated(){
	var m_d = new Date();
	var m_year = m_d.getUTCFullYear();
	var m_month = m_d.getUTCMonth() + 1;
	var m_date = m_d.getUTCDate();
	var m_hour = m_d.getUTCHours();
	var m_minute = m_d.getUTCMinutes();
	var m_second = m_d.getUTCSeconds();

	if(m_month  < 10) m_month = '0' + m_month;
	if(m_date   < 10) m_date = '0' + m_date;
	if(m_hour   < 10) m_hour = '0' + m_hour;
	if(m_minute < 10) m_minute = '0' + m_minute;
	if(m_second < 10) m_second = '0' + m_second;

	return  m_year + '-' + m_month + '-' + m_date + 'T' + m_hour + ':' + m_minute + ':' + m_second + 'Z';
}


/**
*
*  Secure Hash Algorithm (SHA1)
*  http://www.webtoolkit.info/
*
**/
function SHA1(msg) {

    function rotate_left(n,s) {
        var t4 = ( n<<s ) | (n>>>(32-s));
        return t4;
    };

    function lsb_hex(val) {
        var str="";
        var i;
        var vh;
        var vl;

        for( i=0; i<=6; i+=2 ) {
            vh = (val>>>(i*4+4))&0x0f;
            vl = (val>>>(i*4))&0x0f;
            str += vh.toString(16) + vl.toString(16);
        }
        return str;
    };

    function cvt_hex(val) {
        var str="";
        var i;
        var v;

        for( i=7; i>=0; i-- ) {
            v = (val>>>(i*4))&0x0f;
            str += v.toString(16);
        }
        return str;
    };


    function Utf8Encode(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var blockstart;
    var i, j;
    var W = new Array(80);
    var H0 = 0x67452301;
    var H1 = 0xEFCDAB89;
    var H2 = 0x98BADCFE;
    var H3 = 0x10325476;
    var H4 = 0xC3D2E1F0;
    var A, B, C, D, E;
    var temp;

    msg = Utf8Encode(msg);

    var msg_len = msg.length;

    var word_array = new Array();
    for( i=0; i<msg_len-3; i+=4 ) {
        j = msg.charCodeAt(i)<<24 | msg.charCodeAt(i+1)<<16 |
        msg.charCodeAt(i+2)<<8 | msg.charCodeAt(i+3);
        word_array.push( j );
    }

    switch( msg_len % 4 ) {
        case 0:
            i = 0x080000000;
        break;
        case 1:
            i = msg.charCodeAt(msg_len-1)<<24 | 0x0800000;
        break;

        case 2:
            i = msg.charCodeAt(msg_len-2)<<24 | msg.charCodeAt(msg_len-1)<<16 | 0x08000;
        break;

        case 3:
            i = msg.charCodeAt(msg_len-3)<<24 | msg.charCodeAt(msg_len-2)<<16 | msg.charCodeAt(msg_len-1)<<8    | 0x80;
        break;
    }

    word_array.push( i );

    while( (word_array.length % 16) != 14 ) word_array.push( 0 );

    word_array.push( msg_len>>>29 );
    word_array.push( (msg_len<<3)&0x0ffffffff );


    for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {

        for( i=0; i<16; i++ ) W[i] = word_array[blockstart+i];
        for( i=16; i<=79; i++ ) W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);

        A = H0;
        B = H1;
        C = H2;
        D = H3;
        E = H4;

        for( i= 0; i<=19; i++ ) {
            temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=20; i<=39; i++ ) {
            temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=40; i<=59; i++ ) {
            temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=60; i<=79; i++ ) {
            temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        H0 = (H0 + A) & 0x0ffffffff;
        H1 = (H1 + B) & 0x0ffffffff;
        H2 = (H2 + C) & 0x0ffffffff;
        H3 = (H3 + D) & 0x0ffffffff;
        H4 = (H4 + E) & 0x0ffffffff;

    }

    var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);

    return temp.toLowerCase();

}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


};
Gadget.Springnote.OpenBrain.registerClass("Gadget.Springnote.OpenBrain", "Web.Bindings.Base");
Gadget.Springnote.OpenBrain.Events = Web.Enum.create("onGoClick");
